package org.mch.func.file.filename;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import org.apache.commons.io.FileUtils;
import org.mch.biz.ui.FuncEvent;
import org.mch.biz.ui.FuncPanel;
import org.mch.swingm.core.MFileChooser;

import com.mch.main.common.MEnv;

/**
 * 描述：文件操作；
 * 
 * @author MCH；Date：2008-10-01；<BR/>
 * 
 */
public class ClientEvent extends FuncEvent {
	private static final long serialVersionUID = -8590108060646853821L;

	private MFileChooser fileChooser;
	private MFileNameUtils fileNameUtils;

	public ClientEvent(FuncPanel panel) {
		super(panel);
	}

	protected void onButtonClick(ActionEvent e) throws Exception {
		if (e.getSource() == getPanel().getBtnExecute()) {
			execute();
		}
	}

	public void execute() {
		if (getPanel().getSelAddFileNamePrefix().isSelected()) {
			// 增加，前缀
			String filePath = getPanel().getFile_path().getValue();
			String prefix = getPanel().getTextFileNamePrefix().getText();
			boolean isFileAndFolderName = getPanel().getIsFileAndFolderName().isSelected();// 是否包含文件夹
			getFileNameUtils().addNamePrefix(filePath, prefix, isFileAndFolderName);

		} else if (getPanel().getSelAddFileNameSuffix().isSelected()) {
			// 增加，后缀
			String filePath = getPanel().getFile_path().getValue();
			String suffix = getPanel().getTextFileNameSuffix().getText();
			boolean isFileAndFolderName = getPanel().getIsFileAndFolderName().isSelected();// 是否包含文件夹
			getFileNameUtils().addNameSuffix(filePath, suffix, isFileAndFolderName);

		} else if (getPanel().getRdbtn_oldnew().isSelected()) {
			boolean isUpdateFloder = getPanel().getCheck_floder().isSelected();// 是否修改文件夹名
			boolean isSearchChild = getPanel().getCheck_searchchild().isSelected();// 是否搜索子文件夹

			// 要更新的 文件夹
			String folderPath = getPanel().getFile_path().getValue();

			String tmp_reqgz = getPanel().getText_repgz().getText();
			String[] reqgzss = tmp_reqgz.split("\n");

			for (String reqgz : reqgzss) {
				String[] ss = reqgz.split("=");
				String old_str = ss[0];
				if (old_str == null) {
					continue;
				}
				String new_str = ss.length == 1 || ss[1] == null ? "" : ss[1];
				getFileNameUtils().reqlaceFileName(old_str, new_str, new File(folderPath), isUpdateFloder, isSearchChild);
			}

		} else if (getPanel().getRdbtn_zdwjfolder().isSelected()) {
			// 将指定目录下，所有文件夹下，指定的文件类型的文件名改为与其所在文件夹相同

			String filepath = getPanel().getFile_path().getValue();
			File file = new File(filepath);
			File[] files = file.listFiles();

			Map<File, File> fileRenameMap = new HashMap<File, File>();

			String fileType = getPanel().getText_filetype().getText();

			for (File tmpfile : files) {
				if (tmpfile.isDirectory()) {
					// 如果是文件夹，就看看此文件下是否有文件
					File[] childfiles = tmpfile.listFiles();
					for (File childTmpFile : childfiles) {
						if (childTmpFile.getName().toLowerCase().endsWith(fileType.toLowerCase())) {
							reNameFileName(childTmpFile, tmpfile.getName());
						}
					}
				}
			}

			getFileNameUtils().renameFileMap(fileRenameMap);
		} else if (getPanel().getRdbtn_filefoldercount().isSelected()) {
			// 统计目录下，文件和文件夹个数
			long fileCount = 0L;
			String filepath = getPanel().getFile_path().getValue();
			File file = new File(filepath);
			File[] files = file.listFiles();
			fileCount = sumFileFolderCount(files);
			getPanel().getText_filefolder_count().setText(fileCount + "");
		} else if (getPanel().getRdbtn_filetypeedit().isSelected()) {
			editFileType();
		} else if (getPanel().getRdbtn_insertname().isSelected()) {
			insertFileName();
		} else if (getPanel().getRdbtn_filenamenumberedit().isSelected()) {
			fileNameNumberEdit();
		} else if (getPanel().getRdbtn_filenameprefixfolder().isSelected()) {
			String filepath = getPanel().getFile_path().getValue();
			File filePath = new File(filepath);
			fileNamePrefixFolder(filePath);
		} else if (getPanel().getRdbtn_converjsp().isSelected()) {
			String filepath = getPanel().getFile_path().getValue();
			File filePath = new File(filepath);
			String fileType = getPanel().getText_jspcvrtype().getText();
			boolean isContainChild = getPanel().getChx_jspchildfile().isSelected();// 是否包含子目录
			String jspHeader = getPanel().getText_jspheader().getText();
			String encoding = getPanel().getText_encoding().getText();

			converToJSP(filePath, fileType, isContainChild, jspHeader, encoding);

		} else {
			JOptionPane.showMessageDialog(MEnv.MAINFRAME, "请选择要执行的操作！");
		}
	}

	/**
	 * 将对应类型文件，转换为JSP文件；
	 * 
	 * @param filePath
	 * @param isContainChild
	 * @param jspHeader
	 * @param fileType
	 */
	private void converToJSP(File filePath, String oldTypeName, boolean isContainChild, String jspHeader, String encoding) {
		String newTypeName = "jsp";

		File[] files = filePath.listFiles();
		for (File file : files) {
			if (file.isFile() && file.getName().endsWith(oldTypeName)) {
				try {
					String fileText = FileUtils.readFileToString(file, encoding);
					String newFileText = jspHeader + "\n" + fileText;
					FileUtils.writeStringToFile(file, newFileText, encoding);

					getFileNameUtils().editSigleFileType(file, oldTypeName, newTypeName);

				} catch (IOException e) {
					e.printStackTrace();
				}
			} else if (file.isDirectory() && isContainChild) {
				converToJSP(file, oldTypeName, isContainChild, jspHeader, encoding);
			}
		}

	}

	/**
	 * 将文件夹下指定类型文件的文件名前加上文件夹名
	 */
	private void fileNamePrefixFolder(File filePath) {
		boolean isContainChildFolder = getPanel().getCheckBox_prefixfolderchildfolder().isSelected();// 是否包含子文件夹内容

		// 文件夹后追加
		String prefixfolder_append = getPanel().getText_prefixfolder_append().getText();

		// 文件类型
		String fileType = getPanel().getText_prefixfolder_filetype().getText();
		fileType = fileType.startsWith(".") ? fileType : "." + fileType;

		File[] files = filePath.listFiles();

		for (File file : files) {

			if (file.isFile() && file.getName().endsWith(fileType)) {

				File parentfile = file.getParentFile();
				String parentFileName = parentfile.getName();

				String newName = parentFileName + prefixfolder_append + file.getName();

				File newFile = new File(parentfile.getPath() + "\\" + newName);

				getFileNameUtils().editFileName(file, newFile);

			} else if (file.isDirectory() && isContainChildFolder) {
				fileNamePrefixFolder(file);
			}

		}
	}

	/**
	 * 将当前文件夹下所有对应类型文件，按数字顺序重命名；
	 */
	private void fileNameNumberEdit() {
		String filepath = getPanel().getFile_path().getValue();
		File filePath = new File(filepath);

		String fileType = getPanel().getText_filenamenumberedit_type().getText();
		String begin = getPanel().getText_filenamenumberedit_begin().getText();

		File[] files = filePath.listFiles();
		int i = 0;
		for (File file : files) {
			if (!file.getName().endsWith(fileType)) {
				continue;
			}

			String oldname = file.getName();
			String newName = null;
			if (oldname.lastIndexOf(".") > -1) {
				String type = oldname.substring(oldname.lastIndexOf("."), oldname.length());
				newName = (i + Integer.parseInt(begin)) + type;
			} else {
				newName = (i + Integer.parseInt(begin)) + "";
			}

			getFileNameUtils().editFileName(file, new File(file.getParent() + "\\" + newName));

			i++;
		}
	}

	/**
	 * 插入指定位置字符，修改文件名；
	 */
	private void insertFileName() {
		int insertIndex = Integer.parseInt(getPanel().getText_insertindex().getText());
		String insertStr = getPanel().getText_insertstr().getText();

		String filePath = getPanel().getFile_path().getValue();
		getFileNameUtils().insertFileName(new File(filePath), insertIndex, insertStr);
	}

	private void editFileType() {
		String filepath = getPanel().getFile_path().getValue();
		File filePath = new File(filepath);
		String oldTypeName = getPanel().getText_oldfiletype().getText();
		String newTypeName = getPanel().getText_newfiletype().getText();
		boolean isContainChild = getPanel().getChx_childfiletype().isSelected();// 是否包含子目录

		File[] files = filePath.listFiles();
		for (File file : files) {
			getFileNameUtils().editFileType(file, oldTypeName, newTypeName, isContainChild);
		}
	}

	protected long sumFileFolderCount(File[] files) {
		if (files == null || files.length == 0) {
			return 0L;
		}

		long count = 0;
		boolean isSelectFile = getPanel().getChx_baohanfile().isSelected();
		boolean isSelectFolder = getPanel().getChx_baohanfolder().isSelected();
		boolean isSelectFileHide = getPanel().getChx_baohanfilehide().isSelected();
		boolean isSelectFolderHide = getPanel().getChx_baohanfolderhide().isSelected();
		boolean isSelectFolderChild = getPanel().getChx_baohanfolderchild().isSelected();

		for (int i = 0, len = files.length; i < len; i++) {
			File tmpfile = files[i];
			if (tmpfile.isDirectory()) {
				if (tmpfile.isHidden()) {
					if (isSelectFolderHide) {
						if (isSelectFolderChild) {// 包含子目录
							count += sumFileFolderCount(tmpfile.listFiles());
						}
					}
				} else {
					if (isSelectFolderChild) {// 包含子目录
						count += sumFileFolderCount(tmpfile.listFiles());
					}
				}
				if (isSelectFolder) {
					count++;
				}
			} else if (tmpfile.isFile() && isSelectFile) {
				if (tmpfile.isHidden()) {
					if (isSelectFileHide) {
						count++;
					}
				} else {
					count++;
				}
			}
		}

		return count;
	}

	protected void reNameFileName(File file, String newName) {
		reNameFileName(file, newName, null);
	}

	/**
	 * 修改文件名，支持文件或文件夹
	 * 
	 * @param file
	 * @param newName
	 */
	protected void reNameFileName(File file, String newName, String fileType) {
		String oldpath = file.getPath();

		if (file.isDirectory()) {
			// 如果是文件夹，进行如下修改
			String newpath = oldpath.substring(0, oldpath.lastIndexOf(File.separator)) + File.separator + newName;
			File newfile = new File(newpath);
			file.renameTo(newfile);
		} else if (file.isFile()) {
			// 如果是文件，进行如下修改
			String filename = file.getName();
			if (filename.indexOf(".") > 0) {
				String fix = null;
				if (fileType == null || fileType.trim().equals("")) {
					fix = filename.substring(filename.lastIndexOf("."), filename.length());
				} else {
					fix = fileType;
				}
				String folderpath = oldpath.substring(0, oldpath.lastIndexOf(File.separator));
				String newpath = folderpath + File.separator + newName + fix;
				File newfile = new File(newpath);
				file.renameTo(newfile);
			} else {
				String newpath = oldpath.substring(0, oldpath.lastIndexOf(File.separator)) + File.separator + newName;
				File newfile = new File(newpath);
				file.renameTo(newfile);
			}
		} else {

		}

	}

	public void browse() {
		int tmp = getFileChooser().showOpenDialog(MEnv.MAINFRAME);
		if (tmp == JFileChooser.APPROVE_OPTION) {
			getPanel().getFile_path().setText(getFileChooser().getSelectedFile().getPath());
		}
	}

	public MFileChooser getFileChooser() {
		if (fileChooser == null) {
			fileChooser = new MFileChooser();
			fileChooser.setPreferredSize(700, 400);
			fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);// 设置能选择文件和文件夹
		}
		return fileChooser;
	}

	public MFileNameUtils getFileNameUtils() {
		if (fileNameUtils == null) {
			fileNameUtils = new MFileNameUtils();
		}
		return fileNameUtils;
	}

	public ClientPanel getPanel() {
		return (ClientPanel) super.getPanel();
	}
}